package com.xcity.game.item.effect;

import java.text.MessageFormat;

import com.xcity.db.entity.Player;
import com.xcity.game.buff.Buff;
import com.xcity.game.buff.BuffTemplate;
import com.xcity.game.common.MessageConst;
import com.xcity.game.item.GameItem;
import com.xcity.game.item.ItemEffect;
import com.xcity.game.item.ItemException;
import com.xcity.game.item.listener.BagListener;
import com.xcity.game.worldevent.WorldEvent;
import com.xcity.game.worldevent.WorldEventService;

import naga.x.App;
import naga.x.game.template.TemplateService;

public class ExtendWorldEventTimeEffect implements ItemEffect {

	@Override
	public boolean effect(Player player, GameItem item, int count, BagListener listener) throws ItemException {
		int needCount = item.getTemplate().getParameter(0);
		if (count < needCount) {
			throw new ItemException(MessageFormat.format(MessageConst.ITEM_NOT_ENOUGH, item.getName()));
		}
		WorldEventService service = App.getApp().getServiceManager().get(WorldEventService.class);
		WorldEvent event = service != null ? service.getCurrentEvent() : null;
		if (event == null) {
			throw new ItemException(MessageConst.HAVE_NO_WORLD_EVENT);
		}
		int buffId = WorldEventService.buffIdOffset + event.getId();
		Buff buff = player.getBuffs().getBuff(buffId);
		if (buff == null) {
			TemplateService ts = App.getApp().getServiceManager().get(TemplateService.class);
			buff = new Buff(buffId, event.getTime(), 0, ts.get(BuffTemplate.class, buffId));
			player.getBuffs().addBuff(buff);
		}
		int multi = item.getTemplate().getParameter(1);
		buff.setDuration(buff.getDuration() + multi * buff.getDuration());
		return true;
	}

}
